//
//  BCProjectDetailsController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/22.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCProjectDetailsController.h"

//登录
#import "GSCommonLoginViewController.h"
//网页
#import "BCURLController.h"

//cell以及header、footer
#import "BCProjectDetailsFooterView.h"
#import "BCProjectDetailsHeaderView.h"
#import "BCProjectDetailIntroductionCell.h"//产品介绍cell
#import "BCProjectDetailCommonProblemsCell.h"//常见问题
#import "BCProjectDetailJoinRuleCell.h"//参与规则
#import "BCProjectDetailProjectDataCell.h"//头部data
#import "BCProjectDetailJoinPeopleCell.h"//参与人数
#import "BCProjectDetailRichListCell.h"//富豪榜

//分享按钮
#import "BCProjectDetailShareButton.h"
#import "BCShareRewardController.h"

//source
#import "BCProjectDetailSourceModel.h"

//历史数据
#import "BCProjectDetailsHistoryController.h"

//底部操作视图
#import "BCProjectDetailsBottomView.h"

//产品介绍的弹出视图
#import "BCProjectIntroductionView.h"

//refresh
#import "BCRefreshNormalHeader.h"
//购买控制器
#import "BCProjectBuyController.h"
//svip
#import "BCSVIPController.h"

//request
#import "BCProjectDetailRequestModel.h"
#import "BCUserSafeCenterRequest.h"//请求是否设置了支付密码

@interface BCProjectDetailsController () <UITableViewDataSource,UITableViewDelegate,BCProjectDetailsHeaderViewDelegate,BCProjectDetailsBottomViewDelegate,BCProjectDetailsControllerDelegate,BCSVIPControllerDelegate>

@property (nonatomic, strong) UITableView *detailsTable;

/**
 *tableTopView
 */
@property (nonatomic, strong) UIView *tableTopView;

/**
 *shareButton
 */
@property (nonatomic, strong) BCProjectDetailShareButton *shareButton;

/**
 *bottomView
 */
@property (nonatomic, strong) BCProjectDetailsBottomView *bottomView;

/**
 *BCProjectIntroductionView
 */
@property (nonatomic, strong) BCProjectIntroductionView *introductionView;

/**
 *BCRefreshNormalHeader
 */
@property (nonatomic, strong) BCRefreshNormalHeader *refreshHeader;

#pragma mark - BCProjectDetailSourceModel

/**
 *BCProjectDetailSourceModel 管理资源类
 */
@property (nonatomic, strong) BCProjectDetailSourceModel *projectSource;


#pragma mark - BCProjectDetailData

/**
 *requestDetailData
 */
@property (nonatomic, strong) BCProjectDetailData *requestDetailData;

@end

@implementation BCProjectDetailsController

- (BCProjectDetailSourceModel *)projectSource {
    if (!_projectSource) {
        _projectSource = [BCProjectDetailSourceModel new];
    }
    return _projectSource;
}

- (BCRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
        _refreshHeader.animateCircleClolor = [UIColor darkMainColor];
    }
    return _refreshHeader;
}
//
- (BCProjectDetailShareButton *)shareButton {
    if (!_shareButton) {
        _shareButton = [BCProjectDetailShareButton new];
        [self.view addSubview:_shareButton];
        [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.customNaviBar.mas_bottom).offset(15.0);
            make.right.mas_equalTo(self.view);
            make.height.mas_equalTo([BCProjectDetailShareButton defaultHeight]);
        }];
        [self.view layoutIfNeeded];
        //
        [_shareButton addTarget:self action:@selector(shareButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareButton;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.customNaviBar.backgroundColor = [UIColor whiteColor];
    //
    [self setupSubviews];
    
    //
    [self.refreshHeader beginRefreshing];
    //请求一次是否设置了支付密码
    [self requestUserSetPayPass];
}
//
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //
    [self clearIntroductionView];
}
- (void)setMainColor:(UIColor *)mainColor {
    self.customNaviBar.backgroundColor = mainColor;
    self.tableTopView.backgroundColor = mainColor;
    self.refreshHeader.animateCircleClolor = [mainColor qmui_inverseColor];
    [self updateStatusBar];
}


- (void)setupSubviews {
//    [self.customNaviBar.rightButton setTitle:BCLocalizedKey(@"project_detail_histroy") forState:UIControlStateNormal];
    //
    self.detailsTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.detailsTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.detailsTable.backgroundColor = [UIColor separatorViewColor];
    self.detailsTable.showsVerticalScrollIndicator = false;
    self.detailsTable.dataSource = self;
    self.detailsTable.delegate = self;
    [self.view addSubview:self.detailsTable];
    [self.detailsTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view);
    }];
    [self.detailsTable registerClass:BCProjectDetailsFooterView.class forHeaderFooterViewReuseIdentifier:NSStringFromClass(BCProjectDetailsFooterView.class)];
    [self.detailsTable registerClass:BCProjectDetailsHeaderView.class forHeaderFooterViewReuseIdentifier:NSStringFromClass(BCProjectDetailsHeaderView.class)];
    //富豪
    [self.detailsTable registerClass:BCProjectDetailRichListCell.class forCellReuseIdentifier:NSStringFromClass(BCProjectDetailRichListCell.class)];
    //产品介绍
    [self.detailsTable registerClass:BCProjectDetailIntroductionCell.class forCellReuseIdentifier:NSStringFromClass(BCProjectDetailIntroductionCell.class)];
    //常见问题
    [self.detailsTable registerClass:BCProjectDetailCommonProblemsCell.class forCellReuseIdentifier:NSStringFromClass(BCProjectDetailCommonProblemsCell.class)];
    //参与规则
    [self.detailsTable registerClass:BCProjectDetailJoinRuleCell.class forCellReuseIdentifier:NSStringFromClass(BCProjectDetailJoinRuleCell.class)];
    //
    [self.detailsTable registerClass:BCProjectDetailProjectDataCell.class forCellReuseIdentifier:NSStringFromClass(BCProjectDetailProjectDataCell.class)];
    //参与人数
    [self.detailsTable registerClass:BCProjectDetailJoinPeopleCell.class forCellReuseIdentifier:NSStringFromClass(BCProjectDetailJoinPeopleCell.class)];
    
    //设置一个与底部一样d高度的footer
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, [BCProjectDetailsBottomView defaultHeight]+[BCProjectDetailsBottomCountdownView defaultHeight])];
    [self.detailsTable setTableFooterView:footer];
    //refresh
    [self.detailsTable setMj_header:self.refreshHeader];
    //
    self.tableTopView = [UIView new];
    [self.detailsTable addSubview:self.tableTopView];
    [self.tableTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.detailsTable);
        make.width.mas_equalTo(self.detailsTable);
        make.bottom.mas_equalTo(self.detailsTable.mas_top);
        make.height.mas_equalTo(5000.0);
    }];
    //
    [self.detailsTable bringSubviewToFront:self.refreshHeader];
    
    //bottomView
    self.bottomView = [BCProjectDetailsBottomView new];
    self.bottomView.isPreBuy = self.isPreBuy;
    self.bottomView.delegate = self;
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo([BCProjectDetailsBottomView defaultHeight]);
        make.bottom.mas_equalTo(self.view);
    }];
    self.bottomView.alpha = 0;
    self.bottomView.countdownView.backgroundColor = self.detailsTable.backgroundColor;
    //
    [self.view layoutIfNeeded];
}
#pragma mark -
- (void)didClickedNaviRightButton {
    [self toProjectHistoryAction];
}


#pragma mark - 刷新
- (void)refreshHeaderAction {
    [self clearIntroductionView];
    [self requestDetails];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.projectSource.sectionSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    BCProjectDetailSectionModel *sectionModel = self.projectSource.sectionSource[section];
    if (sectionModel.isHandleData) {
        return sectionModel.dataSource.count;
    }else {
        return sectionModel.placeholderNumbres;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCProjectDetailSectionModel *sectionModel = self.projectSource.sectionSource[indexPath.section];
    switch (sectionModel.sectionType) {
        case BCProjectDetailSectionTypeProjectData:
        {
            BCProjectDetailProjectDataCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCProjectDetailProjectDataCell.class)];
            if (sectionModel.isHandleData) {
                cell.backgroundColor = self.customNaviBar.backgroundColor;
                cell.cellData = self.requestDetailData;
            }else {
                cell.backgroundColor = [UIColor whiteColor];
                cell.cellData = nil;
            }
            return cell;
        }
            break;
        case BCProjectDetailSectionTypeJoinPeoples:
        {
            BCProjectDetailJoinPeopleCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCProjectDetailJoinPeopleCell.class)];
            if (sectionModel.isHandleData) {
                cell.backgroundColor = self.customNaviBar.backgroundColor;
                cell.cellData = self.requestDetailData;
            }else {
                cell.backgroundColor = [UIColor whiteColor];
                cell.cellData = nil;
            }
            return cell;
        }
            break;
        case BCProjectDetailSectionTypeRiches:
        {
            BCProjectDetailRichListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCProjectDetailRichListCell.class)];
            cell.cellData = self.requestDetailData;
            return cell;
        }
            break;
        case BCProjectDetailSectionTypeJoinRules:
        {
            BCProjectDetailJoinRuleModel *model;
            if (sectionModel.isHandleData) {
                model = sectionModel.dataSource[indexPath.row];
            }
            BCProjectDetailJoinRuleCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCProjectDetailJoinRuleCell.class)];
            cell.rule = model;
            return cell;
        }
            break;
        case BCProjectDetailSectionTypeProjectIntrduction:
        {
            BCProjectDetailIntroductionModel *model;
            if (sectionModel.isHandleData) {
                model = sectionModel.dataSource[indexPath.row];
            }
            BCProjectDetailIntroductionCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCProjectDetailIntroductionCell.class)];
            cell.introductionModel = model;
            return cell;
        }
            break;
        case BCProjectDetailSectionTypeInstruction:
        {
            
        }
            break;
        case BCProjectDetailSectionTypeCommonProblems:
        {
            BCProjectDetailCommonProblemModel *model;
            if (sectionModel.isHandleData) {
                model = sectionModel.dataSource[indexPath.row];
            }
            BCProjectDetailCommonProblemsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCProjectDetailCommonProblemsCell.class)];
            cell.problem = model;
            return cell;
        }
            break;
        default:
            break;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCProjectDetailSectionModel *sectionModel = self.projectSource.sectionSource[indexPath.section];
    switch (sectionModel.sectionType) {
        case BCProjectDetailSectionTypeProjectData:
        {
            return [BCProjectDetailProjectDataCell defaultHeight];
        }
            break;
        case BCProjectDetailSectionTypeJoinPeoples:
        {
            return [BCProjectDetailJoinPeopleCell defaultHeight];
        }
            break;
        case BCProjectDetailSectionTypeRiches:
        {
            return [BCProjectDetailRichListCell defaultHeight];
        }
            break;
        case BCProjectDetailSectionTypeJoinRules:
        {
            CGFloat height = [tableView fd_heightForCellWithIdentifier:NSStringFromClass(BCProjectDetailJoinRuleCell.class) configuration:^(id cell) {
                BCProjectDetailJoinRuleModel *model;
                if (sectionModel.isHandleData) {
                    model = sectionModel.dataSource[indexPath.row];
                }
                ((BCProjectDetailJoinRuleCell *)cell).rule = model;
            }];
            return height;
        }
            break;
        case BCProjectDetailSectionTypeProjectIntrduction:
        {
            CGFloat height = [tableView fd_heightForCellWithIdentifier:NSStringFromClass(BCProjectDetailIntroductionCell.class) configuration:^(id cell) {
                BCProjectDetailIntroductionModel *model;
                if (sectionModel.isHandleData) {
                    model = sectionModel.dataSource[indexPath.row];
                }
                ((BCProjectDetailIntroductionCell *)cell).introductionModel = model;
            }];
            return height;
        }
            break;
        case BCProjectDetailSectionTypeInstruction:
        {
            
        }
            break;
        case BCProjectDetailSectionTypeCommonProblems:
        {
            CGFloat height = [tableView fd_heightForCellWithIdentifier:NSStringFromClass(BCProjectDetailCommonProblemsCell.class) configuration:^(id cell) {
                BCProjectDetailCommonProblemModel *model;
                if (sectionModel.isHandleData) {
                    model = sectionModel.dataSource[indexPath.row];
                }
                ((BCProjectDetailCommonProblemsCell *)cell).problem = model;
            }];
            return height;
        }
            break;
        default:
            break;
    }
    return 0;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    BCProjectDetailSectionModel *sectionModel = self.projectSource.sectionSource[section];
    switch (sectionModel.sectionType) {
        case BCProjectDetailSectionTypeJoinRules:
        case BCProjectDetailSectionTypeProjectIntrduction:
        case BCProjectDetailSectionTypeInstruction:
        case BCProjectDetailSectionTypeCommonProblems:
        {
            BCProjectDetailsHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass(BCProjectDetailsHeaderView.class)];
            header.delegate = self;
            header.sectionData = sectionModel;
            return header;
        }
            break;
        default:
            break;
    }
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    BCProjectDetailsFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass(BCProjectDetailsFooterView.class)];
    footer.backgroundColor = tableView.backgroundColor;
    return footer;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    BCProjectDetailSectionModel *sectionModel = self.projectSource.sectionSource[section];
    switch (sectionModel.sectionType) {
        case BCProjectDetailSectionTypeJoinRules:
        case BCProjectDetailSectionTypeProjectIntrduction:
        case BCProjectDetailSectionTypeInstruction:
        case BCProjectDetailSectionTypeCommonProblems:
        {
            return [BCProjectDetailsHeaderView defaultHeight];
        }
            break;
        default:
            break;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    BCProjectDetailSectionModel *sectionModel = self.projectSource.sectionSource[section];
    switch (sectionModel.sectionType) {
        case BCProjectDetailSectionTypeRiches:
        case BCProjectDetailSectionTypeJoinRules:
        case BCProjectDetailSectionTypeProjectIntrduction:
        case BCProjectDetailSectionTypeInstruction:
        {
            return 10.0;
        }
            break;
        default:
            break;
    }
    return 0;
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self hiddenIntroductionView];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}

#pragma mark - BCProjectDetailsControllerDelegate
- (void)projectDetailsControllerPreBuySuccessed {
    [self refreshHeaderAction];
}

#pragma mark - BCProjectDetailsHeaderViewDelegate
//section里面的那个按钮被点击
- (void)projectDetailsHeaderView:(BCProjectDetailsHeaderView *)headerView didClickedDetailButtonWithSectionModel:(BCProjectDetailSectionModel *)sectionModel detailButtonConvertFrame:(CGRect)covertFrame {
    if (sectionModel.sectionType==BCProjectDetailSectionTypeProjectIntrduction) {//产品介绍
        [self showProjectIntroductionWithHeaderView:headerView didClickedDetailButtonWithSectionModel:sectionModel detailButtonConvertFrame:covertFrame];
    }
}
//section的button被点击
- (void)projectDetailsHeaderView:(BCProjectDetailsHeaderView *)headerView didClickedBackButtonWithSectionModel:(BCProjectDetailSectionModel *)sectionModel {
    if (self.introductionView) {
        [self hiddenIntroductionView];
    }
    if (sectionModel.sectionURL.length) {
        BCURLController *vc = [BCURLController new];
        vc.urlString = sectionModel.sectionURL;
        [self.navigationController pushViewController:vc animated:true];
    }
}



/**
 显示产品介绍弹出的视图
 */
- (void)showProjectIntroductionWithHeaderView:(BCProjectDetailsHeaderView *)headerView didClickedDetailButtonWithSectionModel:(BCProjectDetailSectionModel *)sectionModel detailButtonConvertFrame:(CGRect)covertFrame {
    if (self.introductionView) {
        [self hiddenIntroductionView];
        return;
    }
    //转换为tableView的frame
    CGRect tableConvertFrame = [headerView convertRect:covertFrame toView:self.detailsTable];
    //转换为view的frame 后面计算用
    CGRect viewConvertFrame = [self.detailsTable convertRect:tableConvertFrame toView:self.view];
    //
    CGFloat showViewWidth = [BCProjectIntroductionView defaultWidth];
    BCProjectIntroductionView *showView = [[BCProjectIntroductionView alloc] initWithFrame:CGRectZero];
    //需要立即约束子视图
    [showView layoutIfNeeded];
    //获取高度
    CGFloat maxHeight = CGRectGetHeight(self.detailsTable.frame)-[BCProjectDetailsBottomView defaultHeight]-20.0;
    CGFloat showViewHeight = [showView heightWithIntroductionData:self.requestDetailData.introduce maxHeight:maxHeight];
    //绘制箭头
    /**
     首先根据height计算出动画的 anchorPoint
     以frame的中心点作为触发 使用viewConvertFrame 计算
     */
    //计算出中心到四边的距离的距离
    CGFloat bottomLast = self.view.frame.size.height-[BCProjectDetailsBottomView defaultHeight]-CGRectGetMidY(viewConvertFrame)-10.0-[BCProjectDetailsBottomCountdownView defaultHeight];//
    CGFloat rightLast = self.view.frame.size.width-8.0-CGRectGetMidX(viewConvertFrame);
    CGFloat topLast = CGRectGetMidY(viewConvertFrame)-CGRectGetHeight(self.customNaviBar.frame);
//    CGFloat leftLast //不用算基本不用
    //开始进行比较 先判断头部部是否够距离
    //showView 顶部预设偏移
    CGFloat showViewYOffset = 25.0;
    //如果头部不足showViewTopOffset不显示
    if (showViewYOffset>topLast) {
        return;
    }
    if (bottomLast<showViewYOffset) {
        return;
    }
    //anchorPointY 底部
    if (showViewHeight-showViewYOffset>bottomLast) {//按预设偏移不足以显示
        //修改x预设偏移
        showViewYOffset = showViewHeight-bottomLast;
    }
    //anchorPointX 右侧
    CGFloat showViewXOffset = 0;
    if (rightLast<showViewWidth) {
        showViewXOffset = showViewWidth-rightLast;
    }
    //
    CGFloat anchorPointX = showViewXOffset/showViewWidth;
    CGFloat anchorPointY = showViewYOffset/showViewHeight;
    //
    showView.layer.anchorPoint = CGPointMake(anchorPointX, anchorPointY);
    //
    [showView setArrowLayerStartPoint:CGPointMake(0, showViewYOffset)];
    //
    showView.frame = CGRectMake(CGRectGetMidX(tableConvertFrame)-showViewXOffset, CGRectGetMidY(tableConvertFrame)-showViewYOffset, showViewWidth, showViewHeight);
    [self.detailsTable addSubview:showView];
    self.introductionView = showView;
    //
    showView.transform = CGAffineTransformMakeScale(0, 0);
    [UIView animateWithDuration:0.2 animations:^{
        showView.transform = CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)hiddenIntroductionView {
    [UIView animateWithDuration:0.1 animations:^{
        self.introductionView.transform = CGAffineTransformMakeScale(0.001, 0.001);
    } completion:^(BOOL finished) {
        [self clearIntroductionView];
    }];
}
- (void)clearIntroductionView {
    if (self.introductionView) {
        [self.introductionView removeFromSuperview];
        self.introductionView = nil;
    }
}


#pragma mark - request
- (void)requestDetails {
    BCProjectDetailRequestModel *request = [BCProjectDetailRequestModel new];
    request.projectId = self.projectId;
    request.isPreBuy = self.isPreBuy;
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.refreshHeader endRefreshing];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCProjectDetailResponse *resp = result;
        [wself reloadData:resp];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorDomain = error.domain;
            [QMUITips showError:errorDomain inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorDomain]];
        }
    }];
    [request requestServer];
}

- (void)reloadData:(BCProjectDetailResponse *)resp {
    self.requestDetailData = resp.data;
}
- (void)setRequestDetailData:(BCProjectDetailData *)requestDetailData {
    _requestDetailData = requestDetailData;
    if (requestDetailData) {
        self.projectSource.isHandleData = true;
        //flow
        if (requestDetailData.data.history_url.length) {
            [self.customNaviBar.rightButton setTitle:requestDetailData.flow.right forState:UIControlStateNormal];
        }
        [self.customNaviBar layoutSubviews];
        //设置title
//        self.customNaviBar.titleLabel.text = requestDetailData.data.project_name;
        if (!self.isPreBuy) {
            self.customNaviBar.titleLabel.text = [requestDetailData.data.project_name stringByAppendingFormat:@"\n%@",requestDetailData.flow.round_str];
        }else {
            self.customNaviBar.titleLabel.text = [requestDetailData.flow.next_buy stringByAppendingFormat:@"\n%@",requestDetailData.data.project_name];
        }
        //设置分享按钮
        [self.shareButton setShareTitle:requestDetailData.share];
        
        //设置主色
        UIColor *color = [UIColor darkMainColor];
        //
        @try {
            color = [UIColor qmui_colorWithHexString:requestDetailData.data.color];
        } @catch (NSException *exception) {
            
        } @finally {
            
        }
        [self setMainColor:color];
        //
        [self.projectSource handleData:requestDetailData];
        //
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self reminderUserNotSVIPBuyCountMaxAction];
        });
    }else {
        
    }
    [self.detailsTable reloadData];
    //
    self.bottomView.projectData = requestDetailData;
}

#pragma mark - 支付相关
/**
 如果用户登录了去请求一次是否设置了支付密码
 */
- (void)requestUserSetPayPass {
    if ([BCUserManager sharedUser].isLogin) {
        //请求一次是否设置了支付密码
        [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
            
        }];
    }
}

#pragma mark - method
/**
 跳转去历史数据
 */
- (void)toProjectHistoryAction {
    BCProjectDetailsHistoryController *history = [BCProjectDetailsHistoryController new];
    history.history = self.requestDetailData.data.history_url;
    [self.navigationController pushViewController:history animated:true];
}

//
- (void)userLoginSuccessedAction:(NSNotification *)noti {
    self.bottomView.alpha = 0;
    [self.refreshHeader beginRefreshing];
    //请求一次是否设置了支付密码
    [self requestUserSetPayPass];
}

#pragma mark - BCProjectDetailsBottomViewDelegate bottomView action
//立即购买
- (void)projectDetailsBottomViewToBuyNowAction {
    //判断是否登录
    if ([BCUserManager sharedUser].isLogin) {
        BOOL canBuy = [self checkSVIPBuy];
        if (canBuy) {
            [self showBuyAction];
        }
    }else {
        [GSCommonLoginViewController presentToCommloginController:self.navigationController];
    }
}
/**
 弹出购买框
 */
- (void)showBuyAction {
    WEAK_SELF
    [BCProjectBuyController showBuyWithData:self.requestDetailData preBuy:false complete:^(NSString *successMsg) {
        [wself.refreshHeader beginRefreshing];
        if (wself.view&&successMsg.length) {
            [QMUITips showSucceed:successMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:successMsg]];
        }
    }];
}

//预购下一轮 跳转去预购界面
- (void)projectDetailsBottomViewToPreBuyAction {
    BCProjectDetailsController *preDetail = [BCProjectDetailsController new];
    preDetail.projectId = self.projectId;
    preDetail.isPreBuy = true;
    preDetail.delegate = self;
    [self.navigationController pushViewController:preDetail animated:true];
}
//立即预购
- (void)projectDetailsBottomViewToPreBuyNowAction {
    //判断是否登录
    if ([BCUserManager sharedUser].isLogin) {
        //
        WEAK_SELF
        [BCProjectBuyController showBuyWithData:self.requestDetailData preBuy:true complete:^(NSString *successMsg) {
            [wself.refreshHeader beginRefreshing];
            if (wself.view&&successMsg.length) {
                [QMUITips showSucceed:successMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:successMsg]];
            }
            if (wself.delegate && [wself.delegate respondsToSelector:@selector(projectDetailsControllerPreBuySuccessed)]) {
                [wself.delegate projectDetailsControllerPreBuySuccessed];
            }
        }];
    }else {
        [GSCommonLoginViewController presentToCommloginController:self.navigationController];
    }
}

#pragma mark - shareButtonDidClickedAction
/**
 分享领奖
 */
- (void)shareButtonDidClickedAction {
    if ([BCUserManager sharedUser].isLogin) {
        [BCShareRewardController showFromController:self.navigationController];
    }else {
        [GSCommonLoginViewController presentToCommloginController:self.navigationController];
    }
}


#pragma mark - 非SVIP用户购买次数处理
/**
 提示用户在非SVIP情况下购买已经达到上限
 */
- (void)reminderUserNotSVIPBuyCountMaxAction {
    BCProjectDetailData *detailData = self.requestDetailData;
    NSInteger userNumber = detailData.data.user_buy_num;
    NSInteger maxNumber = detailData.data.max_buy_num;
    if (userNumber>=0) {
        if (maxNumber>0) {
            if (userNumber>=maxNumber) {//免费购买已达到上限
                NSString *title = detailData.flow.not_svip;
                NSString *message = detailData.flow.not_svip_note;
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                }];
                [alert addAction:cancelAction];
                //
                WEAK_SELF
                UIAlertAction *buyAction = [UIAlertAction actionWithTitle:detailData.flow.buy_svip_note style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [wself toBuySVIPAction];
                }];
                [alert addAction:buyAction];
                [self.navigationController presentViewController:alert animated:true completion:nil];
            }
        }
    }
}

/**
 检查是否可以购买
 */
- (BOOL)checkSVIPBuy {
    BCProjectDetailData *detailData = self.requestDetailData;
    NSInteger userNumber = detailData.data.user_buy_num;
    NSInteger maxNumber = detailData.data.max_buy_num;
    if (userNumber<0) {//未登录重新刷新一次
        NSNotification *noti;
        [self userLoginSuccessedAction:noti];
        return false;
    }
    if (maxNumber>0) {//没有购买SVIP
        if (userNumber>=maxNumber) {//免费购买已达到上限
            NSString *title = detailData.flow.not_svip;
            NSString *message = detailData.flow.not_svip_note;
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:cancelAction];
            //
            WEAK_SELF
            UIAlertAction *buyAction = [UIAlertAction actionWithTitle:detailData.flow.buy_svip_note style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [wself toBuySVIPAction];
            }];
            [alert addAction:buyAction];
            [self.navigationController presentViewController:alert animated:true completion:nil];
            return false;
        }else {
            WEAK_SELF
            NSString *title = detailData.flow.not_svip_note;
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *svipBuyAction = [UIAlertAction actionWithTitle:detailData.flow.buy_svip_note style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [wself toBuySVIPAction];
            }];
            [alert addAction:svipBuyAction];
            //
            UIAlertAction *buyAction = [UIAlertAction actionWithTitle:detailData.flow.status_str.not_buy style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [wself showBuyAction];
            }];
            [alert addAction:buyAction];
            [self.navigationController presentViewController:alert animated:true completion:nil];
            return false;
        }
    }
    //已经购买无限制
    return true;
}
/**
 去购买SVIP
 */
- (void)toBuySVIPAction {
    BCSVIPController *svipVC = [BCSVIPController new];
    svipVC.delegate = self;
    [self.navigationController pushViewController:svipVC animated:true];
}

#pragma mark - BCSVIPControllerDelegate
- (void)buySVIPSuccessedAction {
    NSNotification *noti;
    [self userLoginSuccessedAction:noti];
}

@end
